package com.itheima.travel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itheima.travel.enums.StatusEnum;
import com.itheima.travel.exception.ProjectException;
import com.itheima.travel.req.*;
import com.itheima.travel.res.GetwayRespons;
import com.itheima.travel.service.*;
import com.itheima.travel.session.SubjectSeller;
import com.itheima.travel.session.SubjectSellerContext;
import com.itheima.travel.session.SubjectUser;
import com.itheima.travel.session.SubjectUserContext;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.ExceptionsUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;

/**
 * @Description：API网关服务
 */
@Service
@Log4j2
public class GatewayServiceImpl implements GatewayService {

    @Autowired
    AffixService affixService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    FavoriteService favoriteService;

    @Autowired
    RouteService routeService;

    @Autowired
    UserService userService;

    //@Autowired
    //SellerService sellerService;

    @Autowired
    SubjectUserContext subjectUserContext;

    @Autowired
    SubjectSellerContext subjectSellerContext;

    @Value("${upLoad.webSite}")
    String webSite;

    /**
     *
     * @param method      请求方法
     * @param baseRequest 请求数据
     * @param file 文件上传对象
     * @return
     */
    @Override
    //method=findAllCategory
    public GetwayRespons method(String method, BaseRequest baseRequest, MultipartFile file) {
        //获得请求对象
        Object data = baseRequest.getData();
        String jsonString = null;
        if (!EmptyUtil.isNullOrEmpty(data)){
            //将请求携带的对象转成json字符串
            jsonString = JSONObject.toJSONString(data);
        }
        //转成jsonObejc对象
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        // 封装返回结果
        GetwayRespons result = new GetwayRespons();
        //初始化操作人
        SubjectSeller subjectSeller = subjectSellerContext.getSubject();
        if (!EmptyUtil.isNullOrEmpty(subjectSeller)){
            result.setUserId(subjectSeller.getId());
            result.setUserName(subjectSeller.getUsername());
        }
        SubjectUser subjectUser = subjectUserContext.getSubject();
        if (!EmptyUtil.isNullOrEmpty(subjectUser)){
            result.setUserId(subjectUser.getId());
            result.setUserName(subjectUser.getUsername());
        }
        // 用来封装返回的结果
        Object dataResult = null;
        try {
            switch (method) {
                case "currentSubjectUser":
                    dataResult = subjectUser;
                    break;
                case "currentSubjectSeller":
                    dataResult = subjectUser;
                    break;
                //文件上传
                case "upLoad":
                    dataResult = affixService
                            .upLoad(file,JSONObject.toJavaObject(
                                    jsonObject, AffixVo.class));
                    break;
                //为上传绑定对应的业务Id
                case "bindBusinessId":
                    dataResult = affixService
                            .bindBusinessId(JSONObject.toJavaObject(
                                    jsonObject, AffixVo.class));
                    break;
                //按业务ID查询附件
                case "findAffixByBusinessId":
                    dataResult = affixService
                            .findAffixByBusinessId(JSONObject.toJavaObject(
                                    jsonObject, AffixVo.class));
                    break;
                //用户注册
                case "registerUser":
                    dataResult = userService
                            .registerUser(JSONObject.toJavaObject(
                                    jsonObject, UserVo.class));
                    break;
                //登录
                case "loginUser":
                    dataResult = userService
                            .loginUser(JSONObject.toJavaObject(
                                    jsonObject, UserVo.class));
                    break;
                //登出
                case "loginOutUser":
                    dataResult = true;
                    userService
                            .loginOutUser();
                    break;
                //是否登录
                case "isLogin":
                    dataResult = userService
                            .isLogin();
                    break;
                case "findAllCategory":
                    dataResult = categoryService
                            .findAllCategory();
                    break;
                case "isFavorited":
                    dataResult = favoriteService
                            .isFavorited(JSONObject.toJavaObject(
                                    jsonObject, FavoriteVo.class));
                    break;
                case "addFavorite":
                    dataResult =  favoriteService
                            .addFavorite(JSONObject.toJavaObject(
                                    jsonObject, FavoriteVo.class));
                    break;
                case "findMyFavorite":
                    dataResult =  favoriteService
                            .findMyFavorite(JSONObject.toJavaObject(
                                    jsonObject, FavoriteVo.class),
                                    baseRequest.getPageNum(),
                                    baseRequest.getPageSize());
                    break;
                case "addRoute":
                    dataResult = routeService
                            .addRoute(JSONObject.toJavaObject(
                                    jsonObject, RouteVo.class));
                    break;
                case "findRouteById":
                    dataResult = routeService
                            .findRouteById(JSONObject.toJavaObject(
                                    jsonObject, RouteVo.class));
                    break;
                case "findRouteByPage":
                    dataResult = routeService
                            .findRouteByPage(JSONObject.toJavaObject(
                                    jsonObject, RouteVo.class),
                                    baseRequest.getPageNum(),
                                    baseRequest.getPageSize());
                    break;
               // case "registerSeller":
               //     dataResult = sellerService
               //             .registerSeller(JSONObject.toJavaObject(
               //                     jsonObject, SellerVo.class));
               //     break;
               // case "loginSeller":
               //     dataResult =  sellerService
               //             .loginSeller(JSONObject.toJavaObject(
               //                     jsonObject, SellerVo.class));
               //     break;

                default:
                    log.error("调用：{}接口：不合法",method);
                    result = error(result,new ProjectException("1010","请求不合法"));
                    break;
            }
            //构建返回结果对象
            buildGetwayRespons(result,dataResult, StatusEnum.SUCCEED.getCode(), StatusEnum.SUCCEED.getMsg());
        }catch (Exception e){
            log.error("调用：{}接口出错：{}",method, ExceptionsUtil.getStackTraceAsString(e));
            result = error(result,e);
        }
        return result;
    }

    /**
     * @Description 构建返回参数
     * @param date 返回数据
     * @param code 编码
     * @param msg 消息
     * @return
     */
    private GetwayRespons buildGetwayRespons(GetwayRespons result, Object date, String code, String msg){
        result.setData(date);
        result.setCode(code);
        result.setMsg(msg);
        result.setOperationTime(new Date());
        result.setWebSite(webSite);
        return result;
    }

    @Override
    public GetwayRespons error(GetwayRespons result, Exception e) {
        ProjectException projectException = null;
        if (e instanceof ProjectException){
            projectException = (ProjectException) e;
        }else {
            projectException = new ProjectException(StatusEnum.FAIL.getCode(), StatusEnum.FAIL.getMsg());
        }
        return buildGetwayRespons(result,null,
                projectException.getCode(),
                projectException.getMessage());
    }


}
